package com.ycq.parser;

import com.ycq.parser.mark.DefaultMark;
import lombok.Setter;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.poi.sl.usermodel.PictureData;
import org.apache.poi.xwpf.usermodel.*;

import java.io.*;
import java.util.*;

/**
 * 题库文档解析器
 *
 * @author ycq
 * @date 2025/9/24 13:08
 */
public class QuestionCenterDomScanner implements Closeable {

    private static final QuestionNodeParse NODE_PARSES = new QuestionNodeParse();

    private final String docxPath;
    private final XWPFDocument document;
    private final Iterator<XWPFParagraph> paragraphsIterator;

    private final Set<String> excludeRows = new HashSet<>();

    @Setter
    private EndMark endMark = new DefaultMark();

    public QuestionCenterDomScanner(String docxPath){
        this.docxPath = docxPath;
        try(FileInputStream fis = new FileInputStream(docxPath)){
            this.document = new XWPFDocument(fis);
            this.paragraphsIterator = document.getParagraphs().iterator();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public Optional<QuestionNode> scanNext(){

        // 返回空
        if(!paragraphsIterator.hasNext()){
            return Optional.empty();
        }

        List<String> questionItemLines = new ArrayList<>();
        List<ImageInfo> imageInfoNode = new ArrayList<>();

        boolean questionProcessing = false;

        // 开始题库问题迭代
        PARAGRAPHS_LOOP:  while(paragraphsIterator.hasNext()){
            XWPFParagraph paragraph = paragraphsIterator.next();
            String text = paragraph.getText().trim();

            // 判断是否为结束节点
            if(questionProcessing && endMark.isEnd(text.trim(),paragraph)){
                questionProcessing = false;
                break;
            }
            // 跳过空行
            if(text.trim().isEmpty()){
                questionProcessing = false;
                continue;
            }

            questionProcessing = true;

            // 每行的文本保存
            String[] texts = text.split("\\n");
            for (String s : texts) {
                String trimedText = s.trim();
                if(hasExcludeWords(trimedText)){
                    questionProcessing = false;
                    continue PARAGRAPHS_LOOP;
                }
                questionItemLines.add(trimedText);
            }

            List<XWPFRun> runs = paragraph.getRuns();
            if(CollectionUtils.isNotEmpty(runs)){
                for (XWPFRun run : runs) {
                    List<XWPFPicture> embeddedPictures = run.getEmbeddedPictures();
                    if(CollectionUtils.isNotEmpty(embeddedPictures)){
                        for (XWPFPicture embeddedPicture : embeddedPictures) {
                            XWPFPictureData pictureData = embeddedPicture.getPictureData();

                            // 图片节点
                            String fileName = pictureData.getFileName();
                            byte[] data = pictureData.getData();
                            String fileType = PictureData.PictureType.forNativeID(pictureData.getPictureType()).extension;
                            imageInfoNode.add(new ImageInfo(fileName,fileType,data));
                        }
                    }
                }
            }

        }
        // 没有数据
        if(CollectionUtils.isEmpty(questionItemLines)){
            return Optional.empty();
        }

        // 解析问题节点
        return Optional.ofNullable(NODE_PARSES.parse(questionItemLines,imageInfoNode));
    }

    private boolean hasExcludeWords(String trimedText) {
        for (String excludeRow : excludeRows) {
            if(trimedText.contains(excludeRow)){
                return true;
            }
        }
        return false;
    }

    @Override
    public void close() throws IOException {
        document.close();
    }

    public void addSkipRows(String word) {
        excludeRows.add(word);
    }
}
